<?php

namespace App\Ad\Docking;

use App\Ad\MediaApi\MediaApiBase;
use App\Commons\CommonConstant;
use App\Datalog\AdMonitorLog;
use App\Models\AdMonitor;
use App\Models\AdPlan;
use App\Models\FirstupAd;
use App\Models\Firstups;
use App\Models\Log\LogAdMonitor;
use App\Models\Log\LogAdMonitorInfo;
use App\Models\Log\LogAdPostbackMedia;
use Illuminate\Http\Request;
use YQ\YqExtend;

// 优酷-新睿视-微信小程序
// 对接文档
// https://www.yuque.com/xinruishi/guide/cigv9cn8tilv5vao
class YoukuXyx extends DockingBase
{
    // 点击监控参数
    protected $monitorParams = [
        'idfa'        => '__IDFA__',         // IDFA原始值
        'imei_md5'    => '__IMEI__',         // IMEI原值取MD5摘要
        'oaid'        => '__OAID__',         // OAID原始值，最大长度64位
        'caid'        => '__CAID__',         // caid
        'request_id'  => '__REQUESTID__',    // 本次广告投放的请求id，唯一
        'ip'          => '__IP__',           // 用户ip
        'track_id'    => '__TRACKID__',      // 点击监测上报中附带的广告唯一请求id
        'creative_id' => '__CREATIVEID__',   // 创意id
        'mac'         => '__MAC__',          // 去除分隔符”:”的大写MAC地址取MD5摘要
        'android_id'  => '__ANDROIDID__',    // AndroidID取MD5摘要
        'os'          => '__OS__',           // 0:iOS, 1:Android, 2:Windows, 3:其他
    ];

    // 转化类型映射
    protected $eventTypeMap = [
        CommonConstant::EVENT_FIRSTUP => 'active',
        CommonConstant::EVENT_REG => 'register',
        CommonConstant::EVENT_PAY => 'pay',
    ];

    // 此接口由子类继承
    // 获得点击监控链接拼接参数
    public function getMonitorParams($device_type): string
    {
        return urldecode(http_build_query($this->monitorParams));
    }

    // 此接口由子类继承
    // 处理落地监控数据
    public function handleMonitorInfo(Request $request)
    {
        // 待匹配日志
        $params           = $request->all();
        $log              = LogAdMonitor::suffix(date('Ym'));
        $log->create_time = time();
        $log->plan_id     = $params['plan_id'];
        $log->ip          = $params['ip'] ?? '';
        $log->save();

        // 完整日志
        $info              = LogAdMonitorInfo::suffix(date('Ym'));
        $info->create_time = time();
        $info->plan_id     = $params['plan_id'];
        $info->monitor_id  = $log->id;
        $info->data        = json_encode($params, JSON_UNESCAPED_UNICODE);
        $info->save();

        // 落地日志
        AdMonitorLog::getInstance()->addLog($log, $info);

        return yqok();
    }

    // 此接口由子类继承
    // 是否可以基于ip去匹配数据
    public function needCheckUa()
    {
        return true;
    }

    /**
     * 此接口由子类继承
     * 根据媒体加密方式-生成对应的设备码，用于匹配
     * @param int      $device_type 设备类型
     * @param string[] $device_nums 设备码
     * @return array
     */
    public function getMonitorDeviceNum($device_type, $device_nums): array
    {
        $data = [];
        return $data;
    }

    /**
     * 此接口由子类继承
     * 将用户行为进行api上报转化，如激活注册付费
     *
     * @param int $event_type 事件类型 如激活注册付费
     * @param AdMonitor $monitor
     * @param FirstupAd $firstup_ad
     * @param mixed $mod 事件对应的模型 激活 Firstup 注册 Users 付费 Orders
     * @return int 处理结果状态
     */
    public function postbackToMedia($event_type, AdMonitor $monitor, FirstupAd $firstup_ad, $mod): int
    {
        // 此事件不需要上报
        if (!isset($this->eventTypeMap[$event_type])) {
            return LogAdPostbackMedia::STATUS_NONEED;
        }

        $plan = AdPlan::find($firstup_ad->plan_id);

        // 如果非API自上报则无需处理
        if ($plan['access_type'] != AdPlan::ACCESS_TYPE_API) {
            return LogAdPostbackMedia::STATUS_NOTAPI;
        }

        $monitor_data = json_decode($monitor->data, true);
        $firstup = Firstups::find($firstup_ad->firstup_id);

        if ($event_type == CommonConstant::EVENT_FIRSTUP) {
            $deep_conv = 0;
        } else {
            $deep_conv = 1;
        }
        $params = [
            'event_type'  => $this->eventTypeMap[$event_type],
            'deep_conv'   => $deep_conv,
            'event_time'  => $mod->create_time*1000,
            'track_id'    => $monitor_data['track_id'],
            'creative_id' => $monitor_data['creative_id'],
            'client_ip'   => YqExtend::getServerIp(),
        ];

        // 如果是充值加传金额
        $is_pay = $event_type == CommonConstant::EVENT_PAY;
        if ($is_pay) {
            $params['conv_amount'] = $mod->call_money*100;
        }

        $url = 'https://missile.youku.com/api/ad/conv/v2';
        $res  = MediaApiBase::getInstance()->curl($url, $params, false, true);

        if ($res[0] != 200) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        return LogAdPostbackMedia::STATUS_SUCC;
    }

    // 此接口由子类继承
    // 匹配成功后补齐监控数据
    public function supplementMonitorInfo(FirstupAd $firstup_ad, AdMonitor $monitor)
    {
        $data = json_decode($monitor->data, true);

        $firstup_ad->creative_id = intval($data['creative_id'] ?? 0);  // 创意id
    }
}
